package com.medaxis.hpams.sso.controller;

import com.medaxis.hpams.dto.global.BaseResponse;
import com.medaxis.hpams.dto.global.ErrorException;
import com.medaxis.hpams.dto.global.SuccessResponse;
import com.medaxis.hpams.sso.constant.Constants;
import com.medaxis.hpams.sso.domain.dto.UserDto;
import com.medaxis.hpams.sso.service.UserService;
import com.medaxis.hpams.sso.utils.ResponseUtils;
import com.medaxis.hpams.sso.utils.SecurityUtils;
import com.medaxis.hpams.sso.utils.StringUtils;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController()
@RequestMapping(Constants.VERSION_NUMBER+"/user")
@Api(tags = Constants.VERSION_NUMBER+ "用户管理接口")
public class UserController extends BaseController{

    @Autowired
    ResponseUtils responseUtils;

    @Autowired
    UserService userService;


    @ApiOperation(value = "批量删除用户信息",httpMethod = "DELETE")
    @ApiResponses({@ApiResponse(code = 200, message = "删除成功",response = Integer.class)})
    @ApiImplicitParam(name = "ids", value = "用户ID集合", required = true, paramType="path")
    @DeleteMapping("/{ids}")
    public BaseResponse deletebyid(@ApiParam(value = "删除用户的id数组") @PathVariable Long [] ids){
        return responseUtils.toResponse(userService.deleteUserByIds(ids));
    }

    /**
     * 重置密码
     */
    @ApiOperation(value = "重置密码",httpMethod = "PUT")
    @ApiResponses({@ApiResponse(code = 200, message = "重置成功",response = Integer.class)})
    @PutMapping("/resetPwd")
    public BaseResponse resetPwd(@RequestBody UserDto user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
//        user.setUpdateBy(SecurityUtils.getUsername());
        return new SuccessResponse(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @ApiOperation(value = "修改用户状态",httpMethod = "PUT")
    @ApiResponses({@ApiResponse(code = 200, message = "修改成功",response = UserDto.class)})
    @PutMapping("/changeStatus/{userId}")
    public BaseResponse changeStatus(@PathVariable String userId) {
        UserDto user=userService.selectUserById(Long.valueOf(userId));
        userService.checkUserAllowed(user);
//        user.setUpdateBy(SecurityUtils.getUsername());
        return responseUtils.toResponse(userService.updateUserStatus(user));
    }

    @ApiOperation(value = "修改用户信息",httpMethod = "PUT")
    @ApiResponses({@ApiResponse(code = 200, message = "修改成功",response = UserDto.class)})
    @PutMapping("/update")
    public BaseResponse updatebyid(@ApiParam(value = "待修改的用户信息") @Validated @RequestBody UserDto user){
        userService.checkUserAllowed(user);
        if (Constants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            throw new ErrorException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (Constants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            throw new ErrorException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
//        else if (Constants.NOT_UNIQUE.equals(userService.checkDeptLeaderExit(user))) {
//            throw new ErrorException("该部门下已经存在部门负责人");
//        }
//        user.setUpdateBy(SecurityUtils.getUsername());
        return responseUtils.toResponse(userService.updateUser(user));

    }

    @PostMapping("/add")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功",response = BaseResponse.class)})
    @ApiOperation(value = "添加用户信息",httpMethod = "POST")
    public BaseResponse add(@ApiParam(value = "用户信息")@Validated @RequestBody UserDto user){
        if (Constants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            throw new ErrorException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
//            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (Constants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            throw new ErrorException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (Constants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            throw new ErrorException("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }

//        user.setCreateBy(SecurityUtils.getUsername());
//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
//        Role role = roleService.selectRoleById(user.getRoleId());
//        if (StringUtils.isEmpty(role.getDeptIds())) {
//            //todo enum NUM
//            user.setDeptId(Long.valueOf(1));
//        } else {
//            //todo enum NUM
//            user.setDeptId(role.getDeptIds().get(0));
//        }
        return responseUtils.toResponse(userService.insertUser(user));

    }

    @ApiOperation(value = "根据用户信息查找(用户名称，电话，状态),不分页",httpMethod = "GET")
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功",response = UserDto.class)})
    @GetMapping("/listNoPage")
    public BaseResponse listNoPage(UserDto user) {
        startPage();
        return new SuccessResponse(getDataTable(userService.selectUserList(user)));
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = { "/{userId}"})
    public BaseResponse getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        Map result=new HashMap();
//        result.put("roles", roleService.selectRoleAll());
//        result.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            result.put("data", userService.selectUserById(userId));
//            result.put("postIds", postService.selectPostListByUserId(userId));
//            result.put("roleId", roleService.selectRoleIdByUserId(userId));
        }
        return new SuccessResponse(result);
    }




}
